package oauth.service.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import oauth.repository.mapperadd.SpringSecurityMapper;
import oauth.repository.modelAdd.SysUserRoleRescsDTO;

public class UserDetailsServiceCust implements UserDetailsService
{
	@Autowired
	private SpringSecurityMapper springSecurityMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{
		List<SysUserRoleRescsDTO> upr = springSecurityMapper.selectUPRByUsername(username);
		if (upr == null || upr.size() == 0) { throw new UsernameNotFoundException(""); }

		String password = upr.get(0).getPassword();
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Collection<GrantedAuthority> authorities = new HashSet<>();
		for (SysUserRoleRescsDTO sur : upr)
			authorities.add(new SimpleGrantedAuthority(sur.getRoleName()));

		return new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
	}
}
